package com.hongye.app.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Enumeration;
import java.util.Properties;

import it.sauronsoftware.cron4j.InvalidPatternException;
import it.sauronsoftware.cron4j.Scheduler;

import org.apache.log4j.Logger;

import com.jfinal.plugin.IPlugin;
/**
 * cron4j插件，分配任务
 * @author Administrator
 *
 */
public class Cron4jPlugin implements IPlugin{
	
	private static Logger log = Logger.getLogger(Cron4jPlugin.class);
	private Scheduler scheduler = null;
	private String config = "job.properties";
	private Properties properties;

	public Cron4jPlugin(String config) {
		this.config = config;
	}

	public Cron4jPlugin() {

	}
	@SuppressWarnings({ "rawtypes"})
	public boolean start() {
		scheduler = new Scheduler();
		loadProperties();
		Enumeration enums = properties.keys();
		while (enums.hasMoreElements()) {
			String key = enums.nextElement() + "";
			if (!key.endsWith("job")) {
				continue;
			}
			String cronKey = key.substring(0, key.indexOf("job")) + "cron";
			String enable = key.substring(0, key.indexOf("job")) + "enable";
			if (isDisableJob(enable)) {
				continue;
			}
			String jobClassName = properties.get(key) + "";
			String jobCronExp = properties.getProperty(cronKey) + "";
			Class clazz;
			try {
				clazz = Class.forName(jobClassName);
			} catch (ClassNotFoundException e) {
				throw new RuntimeException(e);
			}
			try {
				
				scheduler.schedule(jobCronExp, (Runnable) clazz.newInstance());
			} catch (InvalidPatternException e) {
				throw new RuntimeException(e);
			} catch (InstantiationException e) {
				throw new RuntimeException(e);
			} catch (IllegalAccessException e) {
				throw new RuntimeException(e);
			}
			scheduler.start();
			if(log.isInfoEnabled()){log.info(jobCronExp + " has been scheduled to run at: " + new Date()
			+ " and repeat based on expression: ");}
		}
		return true;
	}

	private boolean isDisableJob(String enable) {
		return Boolean.valueOf(properties.get(enable) + "") == false;
	}

	private void loadProperties() {
		properties = new Properties();
		InputStream is = Cron4jPlugin.class.getClassLoader()
				.getResourceAsStream(config);
		try {
			properties.load(is);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	public boolean stop() {
		scheduler.stop();
		return true;
	}

	public static void main(String[] args) throws InterruptedException {
		 Cron4jPlugin plugin = new Cron4jPlugin();
		 plugin.start();
		 System.out.println("执行成功！！！");
		 Thread.sleep(5000);
		// plugin.stop();
	}

}
